/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GoogleCredentials.java
 *
 * Created on 15-feb-2011, 10:17:28
 */

package afterubuntu.view;

import afterubuntu.google.GoogleManager;
import afterubuntu.google.GoogleManagerListener;
import afterubuntu.log.Log;
import afterubuntu.pojo.AfterUbuntuData;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JOptionPane;

/**
 *
 * @author Kermit
 */
public class GoogleCredentials extends javax.swing.JDialog implements GoogleManagerListener{

    private AfterUbuntu parent;
    private GoogleManager googleManager;
    private ProvideFeedback provideFeedback;

    private String spread;
    private String work;

    /** Creates new form GoogleCredentials */
    public GoogleCredentials(AfterUbuntu parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.parent = parent;
        feedback.setVisible(false);
        googleManager = null;
        spread = null;
        work = null;
        provideFeedback = null;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        gUsername = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        gPassword = new javax.swing.JPasswordField();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        spreadsheet = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        worksheet = new javax.swing.JTextField();
        ok = new javax.swing.JButton();
        feedback = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("AfterUbuntu");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Google account"));

        jLabel1.setText("Username:");

        gUsername.setNextFocusableComponent(gPassword);
        gUsername.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                gUsernameKeyPressed(evt);
            }
        });

        jLabel2.setText("Password:");

        gPassword.setCaretPosition(gPassword.getPassword().length);
        gPassword.setNextFocusableComponent(spreadsheet);
        gPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                gPasswordKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(gUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(gPassword)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(gUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(gPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("AfetrUbuntu settings"));

        jLabel3.setText("Spreadsheet name:");

        spreadsheet.setNextFocusableComponent(worksheet);
        spreadsheet.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                spreadsheetKeyPressed(evt);
            }
        });

        jLabel4.setText("Worksheet name:");

        worksheet.setNextFocusableComponent(ok);
        worksheet.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                worksheetKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(spreadsheet, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(worksheet)))
                .addContainerGap(12, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(spreadsheet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(worksheet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        ok.setText("OK");
        ok.setNextFocusableComponent(gUsername);
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });
        ok.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                okKeyPressed(evt);
            }
        });

        feedback.setText("Getting information.  ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(feedback)
                        .addGap(18, 18, 18)
                        .addComponent(ok, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ok, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE)
                    .addComponent(feedback))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed
        String username = gUsername.getText();
        String password = new String(gPassword.getPassword());
        if(username.equals("") || password.equals("")){
            JOptionPane.showMessageDialog(this, "Please provide the Google account credentials", "Google account", JOptionPane.WARNING_MESSAGE);
            return;
        }

        spread = spreadsheet.getText();
        if(spread.equals("")){
            JOptionPane.showMessageDialog(this, "Please provide the name of the spreadsheet", "AfterUbuntu settings", JOptionPane.WARNING_MESSAGE);
            return;
        }
        work = worksheet.getText();
        if(work.equals("")){
            JOptionPane.showMessageDialog(this, "Please provide the name of the worksheet", "AfterUbuntu settings", JOptionPane.WARNING_MESSAGE);
            return;
        }

        provideFeedback = new ProvideFeedback();
        Thread th = new Thread(provideFeedback);
        th.start();
        googleManager = new GoogleManager();
        googleManager.addListener(this);
        googleManager.setWorksheetData(username, password, spread, work);
        Thread th2 = new Thread(googleManager);
        th2.start();
        ok.setEnabled(false);
    }//GEN-LAST:event_okActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        System.exit(0);
    }//GEN-LAST:event_formWindowClosing

    private void gUsernameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_gUsernameKeyPressed
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
            okActionPerformed(null);
        }
    }//GEN-LAST:event_gUsernameKeyPressed

    private void gPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_gPasswordKeyPressed
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
            okActionPerformed(null);
        }
    }//GEN-LAST:event_gPasswordKeyPressed

    private void spreadsheetKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_spreadsheetKeyPressed
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
            okActionPerformed(null);
        }
    }//GEN-LAST:event_spreadsheetKeyPressed

    private void worksheetKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_worksheetKeyPressed
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
            okActionPerformed(null);
        }
    }//GEN-LAST:event_worksheetKeyPressed

    private void okKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_okKeyPressed
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
            okActionPerformed(null);
        }
    }//GEN-LAST:event_okKeyPressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel feedback;
    private javax.swing.JPasswordField gPassword;
    private javax.swing.JTextField gUsername;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JButton ok;
    private javax.swing.JTextField spreadsheet;
    private javax.swing.JTextField worksheet;
    // End of variables declaration//GEN-END:variables

    public void requestComplete(int resultCode) {
        provideFeedback.finish();
        feedback.setVisible(false);
        switch(resultCode){
            case GoogleManager.OK:
                feedback.setVisible(true);
                feedback.setText("Done. Loading...");
                AfterUbuntuData afterUbuntuData = googleManager.parseWorksheet();
                if(afterUbuntuData == null){
                    JOptionPane.showMessageDialog(this, "Error reading the worksheet '" + work + "' of the spreadsheet '" + spread + "'. See log for deatils (AfterUbuntu.log)", "AfterUbuntu settings", JOptionPane.ERROR_MESSAGE);
                }else{
                    parent.setAfterUbuntuData(afterUbuntuData);
                    parent.loadAfterUbuntuCategories();
                    persistData();
                    this.dispose();
                }
                break;
            case GoogleManager.ERROR:
                JOptionPane.showMessageDialog(this, "Error getting the spradsheet '" + spread + "'. See log for deatils (AfterUbuntu.log)", "AfterUbuntu settings", JOptionPane.ERROR_MESSAGE);
                break;
            case GoogleManager.BAD_CREDENTIALS:
                JOptionPane.showMessageDialog(this, "Google authentication error", "Google account", JOptionPane.ERROR_MESSAGE);
                break;
            case GoogleManager.MORE_THAN_ONE_SPREADSHEET:
                JOptionPane.showMessageDialog(this, "More than one spreadsheet named '" + spread + "' found", "AfterUbuntu settings", JOptionPane.ERROR_MESSAGE);
                break;
            case GoogleManager.SPREADSHEET_NOT_FOUND:
                JOptionPane.showMessageDialog(this, "Spreadsheet named '" + spread + "' not found", "AfterUbuntu settings", JOptionPane.ERROR_MESSAGE);
                break;
            case GoogleManager.WORKSHEET_NOT_FOUND:
                JOptionPane.showMessageDialog(this, "Worksheet named '" + work + "' not found on spreadsheet '" + spread + "'", "AfterUbuntu settings", JOptionPane.ERROR_MESSAGE);
                break;
        }
        ok.setEnabled(true);
    }

    private void persistData() {
        Properties props = new Properties();
        props.setProperty("gUser", gUsername.getText());
        props.setProperty("spreadsheet", spread);
        props.setProperty("worksheet", work);
        FileOutputStream propsFile = null;
        try {
            propsFile = new FileOutputStream(".AfterUbuntu");
            props.store(propsFile, null);
            //Runtime.getRuntime().exec("attrib +H .AfterUbuntu");
        } catch (FileNotFoundException ex) {
            Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
        } catch (IOException ex) {
            Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
        } finally{
            try{
                if(propsFile != null) propsFile.close();
            } catch (IOException ex){
                Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
            }
        }
    }

    public void loadPersistentData() {
        FileInputStream propsFile = null;
        try {
            Properties props = new Properties();
            propsFile = new FileInputStream(".AfterUbuntu");
            props.load(propsFile);

            gUsername.setText(props.getProperty("gUser"));
            gUsername.setCaretPosition(gUsername.getText().length());
            spreadsheet.setText(props.getProperty("spreadsheet"));
            spreadsheet.setCaretPosition(spreadsheet.getText().length());
            worksheet.setText(props.getProperty("worksheet"));
            worksheet.setCaretPosition(worksheet.getText().length());
        }catch (FileNotFoundException ex) {
            Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
        }catch (IOException ex) {
            Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
        }finally {
            try {
                if(propsFile != null) propsFile.close();
            } catch (IOException ex) {
                Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
            }
        }

        if(gUsername.getText().equals("")) gUsername.requestFocusInWindow();
        else gPassword.requestFocusInWindow();
    }
    // End of variables declaration

    private class ProvideFeedback implements Runnable{

        private boolean finish;

        public ProvideFeedback(){
            finish = false;
        }

        public void run() {
            while(!finish){
                try {
                    if (!feedback.isVisible()) {
                        feedback.setVisible(true);
                    }
                    Thread.sleep(500);
                    if(feedback.getText().equalsIgnoreCase("Getting information.  ")){
                        feedback.setText("Getting information.. ");
                        continue;
                    }
                    if(feedback.getText().equalsIgnoreCase("Getting information.. ")){
                        feedback.setText("Getting information...");
                        continue;
                    }
                    if(feedback.getText().equalsIgnoreCase("Getting information...")){
                        feedback.setText("Getting information.  ");
                        continue;
                    }
                } catch (InterruptedException ex) {
                    Log.getInstance().log(Log.ERROR, ex.getLocalizedMessage());
                }

            }
            //feedback.setVisible(false);
        }

        public void finish(){
            finish = true;
        }

    }
}
